<template>
  <el-dialog
    v-model="dialogVisible"
    :title="$t('team.joinTeam')"
    width="500px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="join-team-content">
      <div class="join-methods">
        <el-radio-group v-model="joinMethod" @change="handleMethodChange">
          <el-radio label="inviteCode">{{ $t('team.joinByInviteCode') }}</el-radio>
          <el-radio label="search" disabled>{{ $t('team.joinBySearch') }}</el-radio>
        </el-radio-group>
      </div>

      <!-- 邀请码加入 -->
      <div v-if="joinMethod === 'inviteCode'" class="invite-code-section">
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-position="top"
        >
          <el-form-item :label="$t('team.inviteCode')" prop="inviteCode">
            <el-input
              v-model="form.inviteCode"
              :placeholder="$t('team.inviteCodePlaceholder')"
              maxlength="16"
              show-word-limit
              clearable
            >
              <template #prepend>
                <el-icon><Key /></el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-form>

        <el-alert
          :title="$t('team.inviteCodeTip')"
          type="info"
          :closable="false"
          show-icon
        >
          {{ $t('team.inviteCodeTipDesc') }}
        </el-alert>
      </div>

      <!-- 搜索加入（暂未实现） -->
      <div v-else-if="joinMethod === 'search'" class="search-section">
        <el-alert
          :title="$t('team.searchJoinComingSoon')"
          type="warning"
          :closable="false"
          show-icon
        >
          {{ $t('team.searchJoinComingSoonDesc') }}
        </el-alert>
      </div>

      <!-- 最近邀请码历史 -->
      <div class="recent-codes" v-if="recentCodes.length > 0">
        <h4>{{ $t('team.recentInviteCodes') }}</h4>
        <div class="code-list">
          <div 
            v-for="code in recentCodes" 
            :key="code"
            class="code-item"
            @click="selectRecentCode(code)"
          >
            <el-icon><Key /></el-icon>
            <span class="code-text">{{ code }}</span>
            <el-button type="text" size="small">
              {{ $t('team.useThisCode') }}
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button 
          type="primary" 
          @click="handleSubmit"
          :loading="loading"
          :disabled="!canSubmit"
        >
          {{ $t('team.joinTeam') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { Key } from '@element-plus/icons-vue'
import { useTeamStore } from '@/stores/teamStore'

interface Props {
  modelValue: boolean
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()
const { t } = useI18n()

const teamStore = useTeamStore()
const formRef = ref<FormInstance>()
const loading = ref(false)
const joinMethod = ref('inviteCode')

// 表单数据
const form = reactive({
  inviteCode: ''
})

// 最近使用的邀请码（从localStorage获取）
const recentCodes = ref<string[]>([])

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 是否可以提交
const canSubmit = computed(() => {
  if (joinMethod.value === 'inviteCode') {
    return form.inviteCode.trim().length > 0
  }
  return false
})

// 表单验证规则
const rules: FormRules = {
  inviteCode: [
    { required: true, message: t('team.inviteCodeRequired'), trigger: 'blur' },
    { min: 6, max: 16, message: t('team.inviteCodeLength'), trigger: 'blur' }
  ]
}

// 方法
const handleMethodChange = () => {
  // 切换加入方式时重置表单
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

const handleSubmit = async () => {
  if (joinMethod.value === 'inviteCode') {
    await handleJoinByInviteCode()
  }
}

const handleJoinByInviteCode = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    
    loading.value = true
    await teamStore.joinTeamByInviteCode(form.inviteCode.trim())
    
    // 保存到最近使用的邀请码
    saveRecentCode(form.inviteCode.trim())
    
    emit('success')
    resetForm()
  } catch (error) {
    console.error('加入团队失败:', error)
  } finally {
    loading.value = false
  }
}

const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    inviteCode: ''
  })
}

const selectRecentCode = (code: string) => {
  form.inviteCode = code
}

const loadRecentCodes = () => {
  try {
    const saved = localStorage.getItem('rickpan_recent_invite_codes')
    if (saved) {
      recentCodes.value = JSON.parse(saved)
    }
  } catch (error) {
    console.error('加载最近邀请码失败:', error)
  }
}

const saveRecentCode = (code: string) => {
  try {
    const codes = recentCodes.value.filter(c => c !== code)
    codes.unshift(code)
    recentCodes.value = codes.slice(0, 5) // 只保留最近5个
    
    localStorage.setItem('rickpan_recent_invite_codes', JSON.stringify(recentCodes.value))
  } catch (error) {
    console.error('保存最近邀请码失败:', error)
  }
}

// 监听对话框打开
watch(dialogVisible, (visible) => {
  if (visible) {
    resetForm()
    loadRecentCodes()
  }
})
</script>

<style scoped lang="scss">
.join-team-content {
  .join-methods {
    margin-bottom: 24px;
    padding: 16px;
    background: var(--el-bg-color-page);
    border-radius: 8px;
  }

  .invite-code-section {
    .el-alert {
      margin-top: 16px;
    }
  }

  .search-section {
    padding: 20px 0;
  }

  .recent-codes {
    margin-top: 24px;
    padding-top: 20px;
    border-top: 1px solid var(--el-border-color-lighter);

    h4 {
      margin: 0 0 12px 0;
      font-size: 14px;
      color: var(--el-text-color-primary);
    }

    .code-list {
      .code-item {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px 12px;
        border: 1px solid var(--el-border-color-lighter);
        border-radius: 6px;
        margin-bottom: 8px;
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
          border-color: var(--el-color-primary);
          background: var(--el-color-primary-light-9);
        }

        .code-text {
          flex: 1;
          font-family: monospace;
          font-size: 14px;
          color: var(--el-text-color-primary);
        }

        .el-icon {
          color: var(--el-color-primary);
        }
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

// 响应式设计
@media (max-width: 768px) {
  :deep(.el-dialog) {
    width: 90% !important;
    margin: 5vh auto;
  }
}
</style>
